package com.gticket.customerbackend.handler;

import com.gticket.customerbackend.pojo.*;
import com.gticket.customerbackend.service.CompanyNameService;
import com.gticket.customerbackend.service.ConsoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Data
@RestController
@Slf4j
@Api(value = "后段控制台Controller" , tags = "控制台handler")
public class ConsoleHandler {

    @Autowired
    private ConsoleService consoleService;
    @Autowired
    private CompanyNameService companyNameService;
    private List<Cinemas> cinemas;
    private List<CinemaHall> cinemaHalls;
    private CinemaOriginalSeatsDTO cinemaOriginalSeatsDTO;

    // 查询所有的电影分院
    @GetMapping("/getAllCinemas")
    @ResponseBody
    @ApiOperation(value = "返回所有的分院",notes = "必传参数: 无")
    public List<Cinemas> getCinemas(String db){
        //模拟用 应该去查了存缓存
        CinemaCode cinemaCode = new CinemaCode();
        cinemaCode.setDb(db);
        cinemas = consoleService.getAllCinemas(cinemaCode);
        log.info("商户：" + db +"登陆了控制台");
        return cinemas;
    }

    //查询分院下的影厅信息
    @GetMapping("/getCinemaHallByCid")
    @ResponseBody
    @ApiOperation(value = "根据输入的cinema_id返回此分院下的所有影厅信息",notes = "必传参数: cinema_id")
    public List<CinemaHall> getCinemaHallByCid(String db,Integer cinema_id){
        //封装对象
        CinemaCode cinemaCode = new CinemaCode();
        cinemaCode.setDb(db);
        cinemaHalls = consoleService.getCinemaHallByCid(cinemaCode,cinema_id);
        log.info("商户:" + db + "查询了编号为" + cinema_id + "号影院下的影厅信息");
        return cinemaHalls;
    }


    //查询分院的影院结构(根据os_id)
    @GetMapping("/getCinemaOriginalSeats")
    @ResponseBody
    @ApiOperation(value = "根据输入的os_id返回此影厅座位信息",notes = "必传参数: os_id")
    public CinemaOriginalSeatsDTO getCinemaOrignalSeats(String db, int os_id)
            throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        //封装对象
        CinemaCode cinemaCode = new CinemaCode();
        cinemaCode.setDb(db);
        // 查询座位表
        CinemaOriginalSeats cinemaOriginalSeats = consoleService.getCinemaOrignalSeats(cinemaCode,os_id);
        // 创建row的list用来存大致的座位顺序给前端使用
        List<String> cinemaseatsrow = new ArrayList<>();
        //使用反射拼接方法，循环调用getter
        Class<?> OriginalSeats = Class.forName("com.gticket.customerbackend.pojo.CinemaOriginalSeats");
        Object obj = OriginalSeats.newInstance();

        // 测试用
        /*
        Method[] methods = OriginalSeats.getMethods();
        System.out.println("开始");
        for(Method m : methods) {
            System.out.println(m);
        }
        System.out.println("结束");
        System.out.println(cinemaOriginalSeats.toString());
        */


        for(int i = 1; i < 16; i++) {
            Method method = OriginalSeats.getDeclaredMethod("getRow_" + i, null);
            String temp = (String) method.invoke(cinemaOriginalSeats);
            if(temp != null ) {
                cinemaseatsrow.add(temp);
            }
        }

        // new DTO函数
        cinemaOriginalSeatsDTO = new CinemaOriginalSeatsDTO();
        // 把需要的数据封装进去
        cinemaOriginalSeatsDTO.setCinemaOriginalSeats(cinemaOriginalSeats);
        cinemaOriginalSeatsDTO.setCinemaOriginalSeatsRows(cinemaseatsrow);
        log.info("商户:" + db + "查询了编号为" + os_id + "号的结构座位表");
        return cinemaOriginalSeatsDTO;
    }

    //从前端接收2维数组并更新数组表
    @PostMapping("/updateSeats")
    @ResponseBody
    @ApiOperation(value = "更新影厅的座位信息",notes = "必传参数: os_id, newSeats")
    public String updateSeats(String db, Integer os_id,
                              String[] newSeats) {
        //测试用数据
        /*
        System.out.println("start============");
        for (int n = 0; n < newSeats.length; n++) {
            System.out.println(newSeats[n]);
        }
        System.out.println("end==============");
         */
        //封装对象
        CinemaCode cinemaCode = new CinemaCode();
        cinemaCode.setDb(db);
        // 对得到的二维数组进行操作
        int length = newSeats.length;
        int innerLength = newSeats[0].length();
        int ch_capacity = 0;
        for (int i = 0; i < length; i++) {
            // 对影厅的容量进行更新
            for (int j = 0; j <innerLength; j++) {
                if(newSeats[i].substring(j,j+1).equals("1")) {
                    ch_capacity++;
                }
            }
            String temp = newSeats[i];
            consoleService.updateSeats(cinemaCode,os_id,(i+1),temp);
        }
        // 在此更新影厅的容量
        consoleService.updateCapacity(cinemaCode,os_id,ch_capacity);
        log.info("商户:" + db + "更新了" + os_id + "号结构座位表");
        return "Success";
    }

    @PostMapping("/insertnewseats")
    @ResponseBody
    @ApiOperation(value = "创建新的座位表",notes = "必传参数: ch_id,newSeats")
    public String InsertNewSeats(String db,Integer ch_id,
                                 String[] newSeats) {
        //封装对象
        CinemaCode cinemaCode = new CinemaCode();
        cinemaCode.setDb(db);
        //往数据库中插入一个空表

        int cinema_id = consoleService.getCinema_idBCh_id(cinemaCode, ch_id);
        if (consoleService.createNewSeats(cinemaCode,cinema_id,ch_id)) {
            //取出刚放入的os_id
            int os_id = consoleService.getOs_idByCh_id(cinemaCode, ch_id);
            int length = newSeats.length;
            int innerLength = newSeats[0].length();
            int ch_capacity = 0;
            for (int i = 0; i < length; i++) {
                // 对影厅的容量进行更新
                for (int j = 0; j <innerLength; j++) {
                    if(newSeats[i].substring(j,j+1).equals("1")) {
                        ch_capacity++;
                    }
                }
                String temp = newSeats[i];
                consoleService.updateSeats(cinemaCode,os_id,(i+1),temp);
            }
            // 在此更新影厅的容量
            consoleService.updateCapacity(cinemaCode,os_id,ch_capacity);
            // 把座位表与影厅表联系起来
            consoleService.connectOS2CH(cinemaCode,os_id,ch_id);
        } else {
            return "创建座位表失败";
        }
        log.info("商户:" + db + "给编号为" + ch_id  + "号影厅新建了一个座位结构表");
        return "成功";
    }

    @PostMapping("/createNewCinemaHall")
    @ResponseBody
    @ApiOperation(value = "创建新的影厅",notes = "必传参数: cinema_id,ch_name")
    public String createNewCinemaHall(String db, Integer cinema_id, String ch_name) {
        //封装对象
        CinemaCode cinemaCode = new CinemaCode();
        cinemaCode.setDb(db);

        if (consoleService.createNewCinemaHall(cinemaCode,ch_name,cinema_id)) {
            log.info("商户:" + db + "在影院" + cinema_id + "号下新建了一个名字为" + ch_name + "的影厅");
            return "成功创建新厅";
        }
            return "创建失败";
    }

    @PostMapping("/createNewCinema")
    @ResponseBody
    @ApiOperation(value = "创建新的分院",notes = "必传参数: cinema_name, company_id, cinema_address")
    public String createNewCinema(String db, String cinema_name, Integer company_id,
                                  String cinema_address){
        //封装对象
        CinemaCode cinemaCode = new CinemaCode();
        cinemaCode.setDb(db);
        if(consoleService.createNewCinema(cinemaCode,cinema_name,company_id,cinema_address)){
            log.info("商户:" + db + "新建了一个名字为" + cinema_name + "的影厅");
            return "成功创建新分院";
        }
        return "创建失败";
    }

    @PostMapping("/uploadLogo")
    @ResponseBody
    public String uploadLogo(String db, MultipartFile picture, HttpServletRequest request) {
        // 对上传的图片在工程目录下进行保存
        String path = request.getServletContext().getRealPath("/");
        File imageFile = new File(path  + "img");

        String picture_name = picture.getOriginalFilename();

        // 不存在则创建文件夹
        if(!imageFile.exists()) {
            imageFile.mkdirs();
        }
        System.out.println("imageFile" + imageFile);

        // 随机生成文件名
        //String fileName = companyNameService.createDataBase(db);
        String fileName = "abc";
        fileName += picture_name.substring(picture_name.indexOf("."));

        //确定该文件的路径
        File upFile = new File(imageFile,fileName );
        // 存放图片
        try{
            picture.transferTo(upFile);
            //log.info("存储图片");
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("logo的路径为：" + upFile);
        return "上传成功";
    }

}
